package com.tarena.micro.service.gateway.filters;

import com.alibaba.nacos.common.utils.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * 练习案例 验证请求是否携带正确的token
 */
@Component
public class AuthenticationFilter implements GlobalFilter {
    /**
        过滤器核心逻辑 验证token
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.验证认证票据是否合法
        Boolean ok=checkToken(exchange);
        //2.判断结果 ok=true放行 ok=false 不放心
        if (ok){
            //token票据没问题
            return chain.filter(exchange);
        }else{
            String jsonData="{\"state\":200,\"message\":\"你被拦截了\",\"data\":null}";
            exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);
            return exchange.getResponse().writeWith(
                    Mono.fromSupplier(()->{
                        return exchange.getResponse().bufferFactory().wrap(jsonData.getBytes(StandardCharsets.UTF_8));
                    })
            );
        }
    }

    private Boolean checkToken(ServerWebExchange exchange) {
        //1.拿到请求对象
        ServerHttpRequest request = exchange.getRequest();
        //2.cookie header query
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        if (!queryParams.isEmpty()){
            String token = queryParams.getFirst("token");
            if (StringUtils.isNotEmpty(token)){
                //token不空 验证正则
                System.out.println("请求token:"+token);
                return token.matches("\\ d{10}");
            }
        }
        return false;
    }
}
